package com.xuzhiguang.baidu.pan.sdk.common.http;

import com.xuzhiguang.baidu.pan.sdk.exception.BaiduPanSdkException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author xuzhiguang
 * @date 2020/6/25 21:41
 */
public class HttpClient {


    private final OkHttpClient okHttpClient;

    public HttpClient(OkHttpClient okHttpClient) {
        this.okHttpClient = okHttpClient;
    }

    public Response execute(Request request) throws BaiduPanSdkException {

        okhttp3.Response response;
        try {
            response = okHttpClient.newCall(convertOkHttpRequest(request)).execute();
        } catch (IOException e) {
            throw new BaiduPanSdkException("[httpClient] okhttp3 发送请求失败", e);
        }

        return convertResponse(response);
    }

    /**
     * 将内部request对象转换为okHttpRequest对象
     * @param request
     * @return
     */
    private okhttp3.Request convertOkHttpRequest(Request request) {

        okhttp3.Request.Builder builder = new okhttp3.Request.Builder();

        StringBuilder url = new StringBuilder(request.getUrl());

        if (request.getParameters() != null && !request.getParameters().isEmpty()) {
            url.append("?").append(HttpUtil.parametersToString(request.getParameters()));
        }

        builder.url(url.toString());

        if (request.getHeaders() != null && !request.getHeaders().isEmpty()) {
            for (Map.Entry<String, String> entry : request.getHeaders().entrySet()) {
                builder.addHeader(entry.getKey(), entry.getValue());
            }
        }

        RequestBody requestBody = null;
        if (request.getContent() != null) {
            requestBody = RequestBody.create(request.getContent());
        }

        builder.method(request.getHttpMethod().toString(), requestBody);

        return builder.build();
    }

    /**
     * 将okHttpResponse转换为内部response
     * @param response
     * @return
     */
    private Response convertResponse(okhttp3.Response response) throws BaiduPanSdkException {
        Response response1 = new Response();
        response1.setStatusCode(response.code());
        try {
            response1.setContent(response.body().bytes());
        } catch (IOException e) {
            throw new BaiduPanSdkException("[httpClient] okhttp3 转换Response失败", e);
        }


        Map<String, String> headers = new LinkedHashMap<>(response.headers().size());
        response.headers().forEach(pair -> {
            headers.put(pair.getFirst(), pair.getSecond());
        });
        response1.setHeaders(headers);

        return response1;
    }

}
